package com.hancher.gamelife2.colockin;

import android.os.Bundle;
import android.view.View;

import androidx.navigation.Navigation;
import androidx.sqlite.db.SimpleSQLiteQuery;

import com.github.gzuliyujiang.wheelpicker.entity.DateEntity;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.hancher.common.androidutil.AsyncUtils;
import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.androidutil.MmkvUtil;
import com.hancher.common.androidutil.ToastUtil;
import com.hancher.common.base.BaseFragment;
import com.hancher.common.javautil.DateUtil;
import com.hancher.common.javautil.EmptyUtil;
import com.hancher.common.room.DbFiliter;
import com.hancher.common.rv.PageRecyclerViewManager;
import com.hancher.gamelife2.R;
import com.hancher.gamelife2.databinding.FragmentColockInListBinding;
import com.hancher.gamelife2.main.MainDatabase_Impl;
import com.lxj.xpopup.XPopup;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.rxjava3.functions.Consumer;

/**
 * 作者 : Hancher ytu_shaoweijie@163.com <br/>
 * 时间 : 2023/3/12 0012 22:49 <br/>
 * 描述 :
 */
public class ColockInListFragment extends BaseFragment<FragmentColockInListBinding> {
    //    private static final String DIARY_LIST_MONTH_FILTER = "DIARY_LIST_MONTH_FILTER";
//    private static final String DIARY_LIST_YEAR = "DIARY_LIST_YEAR";
//    private static final String DIARY_LIST_MONTH = "DIARY_LIST_MONTH";
    private static final String COLOCK_IN_LIST_TYPE_NAME = "COLOCK_IN_LIST_TYPE_NAME";
    private static final String COLOCK_IN_LIST_TYPE_UUID = "COLOCK_IN_LIST_TYPE_UUID";
    private static final String COLOCK_IN_LIST_TYPE_IMAGE = "COLOCK_IN_LIST_TYPE_IMAGE";
    private PageRecyclerViewManager<ColockInPO> prvm;
    DbFiliter filiter = new DbFiliter();


    @Override
    protected void initView(Bundle savedInstanceState) {
        prvm = new PageRecyclerViewManager<ColockInPO>()
                .setContext(getContext())
                .setRecyclerView(binding.recyclerview)
                .setRefreshLayout(binding.refreshLayout)
                .setEnableLoadMore(false)
                .setAdapter(new ColockInListAdapter(MmkvUtil.getString(COLOCK_IN_LIST_TYPE_IMAGE)))
                .setOnItemLongClickListener((baseQuickAdapter, view, i) -> {
                    new XPopup.Builder(getContext()).asConfirm("删除记录", "确定删除此条记录?",
                                    () -> deleteItem(prvm.getRvList().get(i)))
                            .show();
                    return true;
                })
                .setDivider(true)
                .init();


        binding.tvMonthFilter.setText(MmkvUtil.getString(COLOCK_IN_LIST_TYPE_NAME, ""));
        binding.calendarView.setVisibility(View.VISIBLE);

        // 默认初始化日历日期
        int lastYear = DateUtil.getYear();
        int lastMonth = DateUtil.getMonth();
        int lastDay = DateUtil.getDay();
        //请求参数
        filiter.setStart(DateUtil.getFirstStampOfMonth(lastYear, lastMonth, 0));
        filiter.setEnd(DateUtil.getFirstStampOfMonth(lastYear, lastMonth, 1));
        //日历
        binding.calendarView.setSelectEndCalendar(lastYear, lastMonth, lastDay);
        binding.calendarView.setSelectStartCalendar(lastYear, lastMonth, lastDay);
        binding.calendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
            @Override
            public void onCalendarOutOfRange(Calendar calendar) {
                updateListBeforeMonthChange(calendar.getYear(), calendar.getMonth());
            }

            @Override
            public void onCalendarSelect(Calendar calendar, boolean isClick) {
                updateListBeforeMonthChange(calendar.getYear(), calendar.getMonth());
            }
        });
        binding.calendarView.setOnMonthChangeListener(this::updateListBeforeMonthChange);

        //滚动时间
        binding.dateWheelLayout.setRange(DateEntity.yearOnFuture(-50), DateEntity.yearOnFuture(1));
        binding.dateWheelLayout.setDefaultValue(DateEntity.target(lastYear, lastMonth, 0));
        binding.dateWheelLayout.setOnDateSelectedListener((year, month, day) -> updateListBeforeMonthChange(year, month));
    }


    @Override
    protected void initListener() {
        binding.imgEdit.setOnClickListener(v -> {
            Navigation.findNavController(binding.container).navigate(R.id.action_diaryListFragment_to_diaryEditFragment);
        });
        // 弹窗选择类型
        binding.tvMonthFilter.setOnClickListener(v -> {
            AsyncUtils.run(emitter -> {
                String sql = " SELECT * FROM colockintype  WHERE deleteflag!=1 ";
                List<ColockInTypePO> typePOS = MainDatabase_Impl.getInstance().colockInTypeDao().getList(new SimpleSQLiteQuery(sql));
                if (typePOS.size() > 0) {
                    emitter.onNext(typePOS);
                }
                emitter.onComplete();
            }, (Consumer<List<ColockInTypePO>>) typePOS -> {
                List<String> typeStrs = new ArrayList<>();
                for (ColockInTypePO typePO : typePOS) {
                    typeStrs.add(typePO.getTitle());
                }
                new XPopup.Builder(getContext())
                        //.maxWidth(600)
//                        .atView(binding.tvMonthFilter)
                        .hasShadowBg(false)
                        .animationDuration(0)
                        .asCenterList("过滤打卡类型", typeStrs.toArray(new String[typeStrs.size()]),
                                new int[]{},
                                (position, text) -> {
                                    ToastUtil.show("click " + text);
                                    MmkvUtil.put(COLOCK_IN_LIST_TYPE_NAME, typePOS.get(position).getTitle());
                                    MmkvUtil.put(COLOCK_IN_LIST_TYPE_UUID, typePOS.get(position).getUuid());
                                    MmkvUtil.put(COLOCK_IN_LIST_TYPE_IMAGE, typePOS.get(position).getBitmapPath());
                                    ((ColockInListAdapter) prvm.getAdapter()).setImage(typePOS.get(position).getBitmapPath());
                                    binding.tvMonthFilter.setText(typePOS.get(position).getTitle());
                                    queryList();
                                })
                        .show();
            });
        });
    }

    @Override
    protected void initData() {
        queryList();
    }


    //region 查询数据

    /**
     * 月份切换，需要查询
     * @param year
     * @param month
     */
    private void updateListBeforeMonthChange(int year, int month) {
        if (year == DateUtil.getYear(filiter.getStart()) && month == DateUtil.getMonth(filiter.getStart())) {
            return;
        }
        LogUtil.d("选中日期：" + year + "-" + month);

        filiter.setStart(DateUtil.getFirstStampOfMonth(year, month, 0));
        filiter.setEnd(DateUtil.getFirstStampOfMonth(year, month, 1));

        if (binding.dateWheelLayout.getSelectedYear() != year || binding.dateWheelLayout.getSelectedMonth() != month) {
            binding.dateWheelLayout.setDefaultValue(DateEntity.target(year, month, 0));
        }
        if (binding.calendarView.getSelectedCalendar().getYear() != year || binding.calendarView.getSelectedCalendar().getMonth() != month) {
            binding.calendarView.setSelectEndCalendar(year, month, 1);
            binding.calendarView.setSelectStartCalendar(year, month, 1);
            binding.calendarView.scrollToCalendar(year, month, 1);
        }

        queryList();
    }

    /**
     * 查询
     */
    private void queryList() {
        AsyncUtils.run(emitter -> {
            StringBuffer sql = new StringBuffer();
            String typeUuid = MmkvUtil.getString(COLOCK_IN_LIST_TYPE_UUID);
            if (EmptyUtil.isEmpty(typeUuid)) {
                emitter.onNext(new ArrayList<>());
                return;
            }
            sql.append(" SELECT * FROM colockin WHERE deleteflag!=1 AND typeUuid='").append(typeUuid).append("' ");
            sql.append(" AND updateTime BETWEEN ").append(filiter.getStart()).append(" AND ").append(filiter.getEnd()).append(" ");
            sql.append(" ORDER BY createTime ASC ");
            LogUtil.d("sql : " + sql);
            List<ColockInPO> data = MainDatabase_Impl.getInstance().colockInDao().getList(new SimpleSQLiteQuery(sql.toString()));
            if (data == null) {
                data = new ArrayList<>();
            }

            emitter.onNext(data);
        }, (Consumer<List<ColockInPO>>) data -> {
            if (EmptyUtil.isEmpty(data)) {
                ToastUtil.show("所选类型打卡数据为空，请更换类型！");
                prvm.freshData(new ArrayList<>());
                return;
            }
            LogUtil.d("数据库查询到数据：" + data.size());
            prvm.freshData(data);
            updateListAfterDayMonthChange();
        });
    }

    /**
     * 刷新日历
     */
    private void updateListAfterDayMonthChange() {
        Long startStamp = filiter.getStart();
        Long endStamp = filiter.getEnd();
        if (startStamp != null && endStamp != null) {
            List<ColockInPO> colockInPOS = new ArrayList<>();
            Map<String, Calendar> mSchemeDates = new HashMap<>();
            for (ColockInPO item : prvm.getRvList()) {
                if (item.getUpdateTime() != null && item.getUpdateTime() > startStamp && item.getUpdateTime() < endStamp) {
                    colockInPOS.add(item);
                }
                Calendar calendar = new Calendar();
                calendar.setYear(DateUtil.getYear(item.getUpdateTime()));
                calendar.setMonth(DateUtil.getMonth(item.getUpdateTime()));
                calendar.setDay(DateUtil.getDay(item.getUpdateTime()));
                calendar.setScheme("卡 ");
                mSchemeDates.put(calendar.toString(), calendar);
            }
            binding.calendarView.setSchemeDate(mSchemeDates);
        }
    }
    //endregion

    //region 点击条目

    private void deleteItem(ColockInPO deleteItem) {
        AsyncUtils.run(emitter -> {
            deleteItem.setUpdateTime(System.currentTimeMillis());
            deleteItem.setDeleteflag((byte) 1);
            MainDatabase_Impl.getInstance().colockInDao().updateItem(deleteItem);
            emitter.onNext("");
        }, data -> {
            queryList();
        });
    }

    //endregion
}